package model

type AdminMenu struct {
	BaseModel
	Pid    uint   `gorm:"not null;default:0" json:"pid" form:"pid"`
	Title  string `gorm:"not null;default:''" json:"title" form:"title"`
	Icon   string `gorm:"not null;default:''" json:"icon" form:"icon"`
	Type   bool   `gorm:"comment:菜单类型;default:0" json:"type" form:"type"` //true目录 false菜单
	Href   string `gorm:"not null;" json:"href" form:"href"`
	IsShow bool   `gorm:"not null;default:0;" json:"is_show" form:"is_show"` //true 显示 false 隐藏
	Sort   uint   `gorm:"not null;default:0;" json:"sort" form:"sort"`
}

// 对外接口
type AdminMenuApi struct {
	AdminMenu
	Children []AdminMenuApi   `json:"children"`
	CheckArr map[string]uint8 `json:"checkArr"`
}

type AdminMenuApis []AdminMenuApi

func (con AdminMenuApis) GetTree() AdminMenuApis {

	var roots, childs []AdminMenuApi

	for _, v := range con {

		v.Icon += " layui-icon "
		if v.Pid == 0 {
			roots = append(roots, v)
		} else {
			childs = append(childs, v)
		}
	}

	var allTree []AdminMenuApi

	for _, v := range roots {

		//遍历每一个顶级节点,处理所有下级的childs
		recursiveChilds(&v, childs)
		allTree = append(allTree, v)
	}

	return allTree
}

// 递归处理下级
func recursiveChilds(r *AdminMenuApi, nodes []AdminMenuApi) {
	for _, v := range nodes {
		//跳过顶级节点
		if v.Pid == 0 {
			continue
		}
		//判断是否是他的下级
		if r.ID == v.Pid {
			//是他的下级，定义childs
			ChildsTree := &v
			//继续递归该下级，向下查找
			recursiveChilds(ChildsTree, nodes)
			//处理完后
			r.Children = append(r.Children, *ChildsTree)
		}
	}
}
